GBML manual / Maths

approach

Moves start toward end by step, and never overshoots - landing exactly on end once step would carry it past.

Syntax

approach(start, end, step) -> real

Arguments

NameType
startreal
endreal
stepreal

Returns

real

Description

Moves start toward end by step, and never overshoots - once step would carry it past end, this lands exactly on end instead and stays there. step is always a plain distance, never signed; which direction to move is worked out from start and end themselves, so the same positive step works whether the value needs to rise or fall.

approach hands back a real, even when every number is whole. For something counted - a score display catching up with the real score - use approach_int, which keeps the answer a whole number.

Example

x = approach(x, xstart, 2);

Moves this object 2 pixels closer to wherever it spawned, every frame, and stops there for good once it arrives - unlike stepping with sign (see that page for the difference), there is no overshoot to correct for afterward: once x is within 2 pixels of xstart, this returns xstart exactly instead of stepping past it.

A step of 0, or already there

A step of 0 makes no progress at all - approach just returns start unchanged. If start already equals end, the result is end either way, no matter what step is.

Measured, not assumed

approach is a real built-in, not a GBML script, because the difference is measurable: on real hardware, a constexpr built-in doing this exact computation costs about 23% less CPU than the identical logic written as a GBML script (min/max used the same way, just from inside a script instead of the engine) - a script call cannot be inlined away the way a built-in defined right where it's used can be. See angle_approach for the same idea, turning the short way around a circle instead of moving in a straight line.

Cost

A comparison and a min/max call - cheap enough for every frame, on as many values as a project needs eased toward a target at once.

On the GBA

min(start + step, end) when start is below end, max(start - step, end) otherwise - step is a MAGNITUDE, never signed; which direction to move is worked out from start/end themselves. A step of 0 makes no progress. Measured, not assumed: a constexpr built-in doing exactly this costs about 23% LESS CPU than the identical logic written as a GBML script, because a built-in defined here inlines away to zero call overhead at the generated call site, where a script is a genuine out-of-line call even under this project’s own -flto. See angle_approach for the same idea turning the short way around a circle instead of moving in a straight line. It hands back a real, even when every number is whole: for something counted, such as a score display catching up, approach_int keeps the answer a whole number.

See also: angle_approachminmaxsignapproach_int